package com.example.service;

import com.example.Random;
import com.example.mapper.StudentMapper;
import com.example.mapper.TeacherMapper;
import com.example.model.Student;
import com.example.model.Teacher;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TeacherService {
    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;
    @Autowired
    public TeacherService(TeacherMapper teacherMapper,StudentMapper studentMapper) {
        this.teacherMapper = teacherMapper;
        this.studentMapper = studentMapper;
    }

    public String login(HttpServletResponse response,String number, String teacherPassword) {
        Teacher teacher = teacherMapper.findBynumber(number);
        if (teacher!=null&&teacher.getTeacherPassword().equals(teacherPassword)) {
            Cookie autoLoginCookie = new Cookie("id", teacher.getTid());
            Cookie autoLoginCookie1 = new Cookie("name", teacher.getTeacherName());
            //cookie的存在时间
            autoLoginCookie.setMaxAge(30 * 60); // 设置Cookie的有效期，单位为秒
            autoLoginCookie.setPath("/"); // 设置Cookie的路径，使其在整个应用程序中都有效
            autoLoginCookie1.setMaxAge(30 * 60); // 设置Cookie的有效期，单位为秒
            autoLoginCookie1.setPath("/"); // 设置Cookie的路径，使其在整个应用程序中都有效
            response.addCookie(autoLoginCookie);
            response.addCookie(autoLoginCookie1);

            return "success";
        }
        return "field";
    }



    public String register(Teacher teacher) {
        Teacher teacherResult = teacherMapper.findBynumber(teacher.getNumber());
        Student student = studentMapper.findByNumber(teacher.getNumber());
        teacher.setTid(Random.rom());
//        输入电话号码/邮箱号返回结果为空值说明该账号并没有注册
        if(teacherResult==null && student==null) {
            teacherMapper.insertTeacher(teacher);
            return "success";
        }
        return "filed";
    }
    public void update(String number,String teacherPassword){
        teacherMapper.updateTeacher(number,teacherPassword);
    }
    public Teacher select(String number){
       return teacherMapper.findBynumber(number);
    }
    public void updateTeacherInfo(Teacher teacher){
        teacherMapper.changeTeacher(teacher);
    }
}